import turbogears as tg
from turbogears import controllers, expose, flash, validators, redirect, validate
from turbogears.widgets import WidgetsList, TableForm, AutoCompleteTextField, HiddenField, CalendarDatePicker
from bookloantracker.model import *
import logging
log = logging.getLogger("bookloantracker.loan")

from cherrypy import session
import datetime

from bookcadaster import loanHistoryGrid

class LoanFormList(WidgetsList):
    loaner = AutoCompleteTextField(label=_("Loaner"),
                                   validator=validators.NotEmpty(),
                                   search_controller="/acGetLoaner",
                                   search_param="loanerName",
                                   result_name="matches",
                                   only_suggest=True,
                                   show_spinner=False,
                                   attrs={"size":"70"})
    startDate = CalendarDatePicker(label=_("Start date"),
                                   format="%d/%m/%Y",
                                   calendar_lang="pt_BR",
                                   button_text=(_("Choose")))
    bookId = HiddenField()
    
loanForm = TableForm(
    fields = LoanFormList(),
    action = "save",
    submit_text = _("Loan")
    )


class LoanEngine(controllers.Controller):
    @expose()
    def default(self, *k, **kw):
        redirect(tg.url("/"))


    @expose(template="bookloantracker.templates.loan")
    def index(self, id):
        book = Book.get(id)
        log.debug("Book: %r" % book)
        return dict(book=book,
                    loanForm = loanForm,
                    loanHistoryGrid = loanHistoryGrid,
                    values = {"bookId":book.id})

    @expose()
    @validate(validators={"startDate": validators.DateConverter(month_style="dd/mm/yyyy")})
    def save(self, **kw):
        if "loaner" in kw:
            self.populateSessionForm(**kw)
        if not "loaner" in session or not session["loaner"]:
            flash("Invalid request")
            redirect(tg.url("/"))
        book = Book.get(session["bookId"])
        if book.isLoaned:
            flash(_("Book not availiable"))
            redirect(tg.url("/"))
        loaner = session["loaner"].strip()
        loanerDb = Loaner.select(LIKE(Loaner.q.name,loaner))
        if not loanerDb.count():
            flash(_("I don't know this person, please, give informations"))
            redirect("/loaner/index",{"name":loaner,
                                      "ret":"loan.save"})
        loaner = loanerDb[0]
        if session["startDate"]:
            startDate = session["startDate"]
        else:
            startDate = datetime.datetime.now()
        log.debug("startDate %r" % startDate)
        loan = Loan(book=book,
                    loaner = loaner,
                    start = startDate,
                    stop = None)
        flash(_("Book loaned"))
        redirect(tg.url("/"))

    @expose()
    def returnBook(self, id):
        book = Book.get(id)
        if not book.isLoaned:
            flash(_("Book not loaned"))
            redirect(tg.url("/"))
        book.lastOpenLoan.stop = datetime.date.today()
        flash(_("Book returned"))
        redirect(tg.url("/"))
        
    def populateSessionForm(self, loaner, bookId, startDate):
        session['loaner'] = loaner
        session['bookId'] = bookId
        log.debug("Saving startDate session: %s" % type(startDate))
        session['startDate'] = startDate

    def cleanSessionForm(self):
        session['loaner'] = None
        session['bookId'] = None
        session['startDate'] = None        
        
